//
//  JQFXHMsgeeCodeBtn.swift
//  RongYiHua
//
//  Created by 卢小艳 on 2025/7/13.
//

import Foundation
import UIKit

class JQFXHMsgeeCodeBtn: UIButton {
    
    private var jqfxhhhTimer: Timer?
    private var jqfxhOrgiiTitle: String = "发送验证码"
    private var jqfxhTotaljjSeconds: Int = 60
    private var jqfxhRemainkkSeconds: Int = 0

    
    @objc private func jqfxhUpdateCountdown() {
        jqfxhRemainkkSeconds -= 1
        jqfxhUpdatemmTitle()
        
        if jqfxhRemainkkSeconds <= 0 {
            jqfxhStopCountnndown()
        }
    }
    
    func jqfxhStartCountlldown(seconds: Int = 60) {
        self.jqfxhRemainkkSeconds = seconds
        self.jqfxhTotaljjSeconds = seconds
        self.jqfxhOrgiiTitle = self.title(for: .normal) ?? "发送验证码"
        self.isEnabled = false
        DispatchQueue.main.async {
            self.jqfxhUpdatemmTitle()
        }
        
        jqfxhhhTimer = Timer.scheduledTimer(timeInterval: 1.0,
                                     target: self,
                                     selector: #selector(jqfxhUpdateCountdown),
                                     userInfo: nil,
                                     repeats: true)
        RunLoop.main.add(jqfxhhhTimer!, forMode: .common)
    }
    
    private func jqfxhUpdatemmTitle() {
        self.setTitle("\(jqfxhRemainkkSeconds)s", for: .disabled)
    }
    
    func jqfxhStopCountnndown() {
        jqfxhhhTimer?.invalidate()
        jqfxhhhTimer = nil
        self.setTitle(jqfxhOrgiiTitle, for: .normal)
        self.isEnabled = true
    }
    
    
    
    deinit {
        jqfxhhhTimer?.invalidate()
    }
}
